<template>
  <div style="height: 100%;width: calc(100% - 40px);">

    <div class="commentIconFixed">
      <!--      收藏、取消收藏-->
      <div class="commentIcon">
        <img :src="collectImg" @click="toCollect">
        <div>{{ myObj.starCount }}</div>
      </div>
      <div class="commentIcon" style="margin-top: 10px;">
        <img src="assets/theme/img/comment_img.png" @click="toComment">
        <div>{{ myObj.commentCount }}</div>
      </div>
      <div class="commentIcon" style="margin-top: 10px;">
        <img :src="agreeImg" @click="agreeOrNotAgree(true)">
        <div>{{ myObj.agreeCount }}</div>
      </div>
      <div class="commentIcon" style="margin-top: 12px;">
        <img :src="notAgreeImg" @click="agreeOrNotAgree(false)">
        <div>{{ myObj.notAgreeCount }}</div>
      </div>
    </div>

    <el-row :span="24">
      <el-col :span="13" style="line-height: 34px;">
        <i
          style="font-weight: 700;font-size: 16px;margin-right: 20px;cursor: pointer"
          class="el-icon-arrow-left"
          @click="returnPage"
        />
        <span style="font-weight: 700;font-size: 16px;">{{ myObj.title }}</span>
      </el-col>
<!--      <el-col :span="11" style="text-align: right">-->
<!--        <el-button v-if="permission.workbenchKbpUpdate" type="primary" size="small" @click="editArticle">修改</el-button>-->
<!--        <el-button v-if="permission.workbenchKbpDelete" type="primary" size="small" style="margin-left: 5px;" @click="delArticle">删除</el-button>-->
<!--      </el-col>-->
    </el-row>
    <el-divider style="margin: 10px;" />

    <el-row :span="24" class="know-title">
      <el-col :span="9">
        <span class="line-height">{{ myObj.realName }} • 发表于：{{ myObj.createTime }}</span>
      </el-col>
      <el-col :span="7">
        <span>业务类型：</span>
        <span class="line-height">{{ myObj.businessNames }}</span>
      </el-col>
      <el-col :span="8">
        <span>关键字：</span>
        <span class="line-height">{{ myObj.keyWord }}</span>
      </el-col>
    </el-row>

    <el-row v-if="myObj.summary" :span="24" class="know-title">
      <el-col class="line-height" :span="3"><strong>摘要：</strong></el-col>
      <el-col class="line-height" :span="21">
        {{ myObj.summary }}
      </el-col>
    </el-row>

    <el-row :span="24" class="know-content">
      <el-col class="line-height" :span="24"><strong>正文：</strong></el-col>
      <el-col :span="24" v-if="resourceType == 4">
        <iframeViewFile style="height: 695px;background-color:#fff;"></iframeViewFile>
      </el-col>
      <el-col v-if="resourceType != 4" class="line-height" :span="24" style="text-indent: 24px">
        <mavon-editor
          ref="md"
          v-model="myObj.content"
          :box-shadow="false"
          :toolbars-flag="false"
          :image-click="clickImg"
          default-open="preview"
          :subfield="false"
          preview-background="#ffffff"
        />
      </el-col>
    </el-row>
    <el-row :span="24" class="know-title">
      <el-col class="line-height" :span="3"><strong>附件：</strong></el-col>
      <el-col class="line-height" :span="21">
        <div
          v-for="file in myObj.knowledgeArticleFileList"
          style="cursor: pointer;float: left;line-height: 30px;"
          @click="download(file)"
        >
          <i class="el-icon-document-add" style="padding-left: 5px;" />
          <span style="margin-left: 10px;">{{ file.name }}</span>
        </div>
      </el-col>
    </el-row>
    <el-row v-if="permission.aiSwitch && linkKnowSwitch" :span="24" class="know-title">
      <el-col class="line-height" :span="24"><strong>关联知识</strong></el-col>
      <el-col :span="24">
        <el-row style="margin-top: 10px;">
          <el-col :span="24">
            <div id="graphDiv" style="width:100%;height:500px;clear: both" />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row :span="24" class="know-title">
      <el-col class="line-height" :span="24"><strong>评论</strong></el-col>
      <el-col :span="24">
        <el-row id="commentRow">
          <el-col :span="21">
            <el-input
              v-model="content"
              style="border-radius: 0px;"
              placeholder="写下你的评论..."
              size="small"
              resize="none"
              maxlength="300"
            />
          </el-col>
          <el-col :span="2" style="text-align: right">
            <el-button type="primary" size="small" @click="addComment">发 布</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row :span="24">
      <div v-for="(c, index) in myObj.commentList" :key="index" class="commentDiv">
        <el-col style="width: 40px;height: 40px;margin: 5px 5px 10px 0px;">
          <img
            v-if="c.avatar"
            :src="headImgUrl + c.avatar"
            onerror="this.src = 'assets/theme/img/default_user_avatar.png'; this.onerror = null;"
          >
          <img v-else src="assets/theme/img/default_user_avatar.png">
        </el-col>
        <el-col style="width: calc(100% - 50px);float: right;">
          <el-col :span="12" class="commentName" style="height:33.6px;width:50%;">{{ c.realName }}</el-col>
          <el-col :span="12" class="commentName" style="text-align: right;">{{ c.createTime }}</el-col>
          <el-col :span="24" class="line-height">{{ c.content }}</el-col>
          <el-col v-if="c.canDelete == 1" :span="24" style="text-align: right;line-height: 20px;">
            <i class="el-icon-delete" style="cursor: pointer" @click="delComment(c.id)" />
          </el-col>
        </el-col>
        <div v-if="index !== 0" :span="24">
          <el-divider />
        </div>
      </div>
    </el-row>
    <div v-if="previewImg" class="preImg" @click.self="previewImg=null" @mousewheel="imgZoom">
      <el-button style="width: 80px;height: 40px;padding:2px;color:#9B9B9B;text-align: center;position: absolute;top:6%;left:50%;z-index: 999;" @click="cancelView">关闭预览</el-button>
      <img id="preImgItem" :src="previewImg" v-dialogDrag/>
    </div>
  </div>
</template>

<script>
  import { getArticleById, delArticle, addComment, collectOrNotCollect, delComment, agreeOrNotAgree,  getExcelData, changeToPdf} from '@/api/kbp'
  import { mapGetters } from 'vuex'
  import echarts from 'echarts'
  import iframeViewFile from '@/views/kbp/iframeView/index'
  export default {
    name: 'ArticleDetail',
    data() {
      return {
        linkKnowSwitch: !window.Settings.multiTenantSwitch,
        id: this.$route.query.id,
        myObj: {},
        tags: [],
        content: '',
        headImgUrl: window.CONFIG.restIps + '/eurm/if/base/file/public/getFilePreview?code=',
        agreeImg: 'assets/theme/img/agree_img.png',
        notAgreeImg: 'assets/theme/img/not_agree_img.png',
        collectImg: 'assets/theme/img/default_collect.png',
        resourceType: '',
        previewImg: null,
        temp: 1,
      }
    },
    computed: {
      ...mapGetters(['permission'])
    },
    watch: {
      '$route': {
        immediate: true,
        handler(to, from) {
          if (to.name === 'kbpDetail') {
            console.log('detail watch route!!!')
            this.id = to.query.id || sessionStorage.getItem('knowledgeId')
            // 在mounted调用的methods里的方法
            this.myObj = {}
            this.initData()
          }
        }
      }
    },
    mounted() {
      this.resourceType = this.$route.query.resourceType
    },
    components: {
      iframeViewFile
    },
    methods: {
      // 收藏、取消收藏
      toCollect() {
        let type = 1
        if (this.myObj.starStatus == 1) {
          type = 2
        }
        const params = {
          type: type,
          knowledgeArticleId: this.id
        }
        collectOrNotCollect(params).then(res => {
          if (res.data.code == 200) {
            this.initData()
            this.$message({ message: params.type == 1 ? '收藏成功！' : '取消收藏成功！', type: 'success' })
          }
        })
      },
      // 取消选择
      cancelSelect () {
        document.selection && document.selection.empty && (document.selection.empty(), 1) ||
        window.getSelection && window.getSelection().removeAllRanges()
      },
      // 点击图片
      clickImg (event) {
        const ev = event || window.event
        this.previewImg = ev.src
        this.cancelSelect()
        return false
      },
      // 获取鼠标位置
      mouseCoords (ev) {
        if (ev.pageX || ev.pageY) {
          return { x: ev.pageX, y: ev.pageY }
        }
        return {
          x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
          y: ev.clientY + document.body.scrollTop - document.body.clientTop
        }
      },
      // 图片缩放
      imgZoom (event) {
        const ev = event || window.event
        const item = document.getElementById('preImgItem')
        let zoom = this.temp
        const numY = this.mouseCoords(ev).y
        let pointY = parseInt(numY / document.body.clientHeight * 100)
        if (pointY > 50) {
          pointY += 10
        } else {
          pointY -= 10
        }
        if (ev.wheelDelta > 0) {
          zoom += 0.2
        } else {
          (zoom > 1) && (zoom -= 0.2)
        }
        this.temp = zoom
        item.style.top = '0px'
        item.style.transform = 'scale(' + zoom + ',' + zoom + ')'
        item.style.transformOrigin = '50% ' + pointY + '% 0'
        ev.stopPropagation()
      },
      // 关闭预览
      cancelView() {
        this.previewImg = null
      },
      // 跳转到评论界面
      toComment() {
        const returnEle = document.querySelector('#commentRow')
        if (returnEle) {
          returnEle.scrollIntoView(true)
        }
      },
      // 点赞/取消点赞(1赞2踩3取消赞4取消踩5赞->踩6踩->赞)
      agreeOrNotAgree(flag) {
        const that = this
        if (that.myObj.agreeStatus == 0 && that.myObj.notAgreeStatus == 0) {
          flag ? that.type = 1 : that.type = 2
        } else if (that.myObj.agreeStatus == 0 && that.myObj.notAgreeStatus == 1) {
          flag ? that.type = 6 : that.type = 4
        } else if (that.myObj.agreeStatus == 1 && that.myObj.notAgreeStatus == 0) {
          flag ? that.type = 3 : that.type = 5
        }
        const params = {
          type: that.type,
          knowledgeArticleId: that.id
        }
        agreeOrNotAgree(params).then(res => {
          if (res.data.code == 200) {
            let message = '点赞成功！'
            if (that.type == 3) {
              message = '取消点赞成功！'
            } else if (that.type == 2 || that.type == 5) {
              message = '点踩成功！'
            } else if (that.type == 4) {
              message = '取消点踩成功！'
            }
            console.log('type is: ' + that.type)
            that.$message({ message: message, type: 'success' })
            that.initData()
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 删除评论
      delComment(id) {
        const that = this
        const params = {
          id: id,
          knowledgeArticleId: that.id
        }
        delComment(params).then(res => {
          if (res.data.code == 200) {
            that.$message({ message: '删除成功', type: 'success' })
            that.initData()
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 发布评论
      addComment() {
        const that = this
        const params = {
          content: that.content,
          knowledgeArticleId: that.id
        }
        if (!that.content) {
          that.$message({ message: '请填写评论内容', type: 'warning' })
          return
        }
        addComment(params).then(res => {
          if (res.data.code == 200) {
            that.$message({ message: '评论成功', type: 'success' })
            that.content = ''
            that.initData()
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 返回上一页
      returnPage() {
        const path = '/kbp'
        this.$router.push({
          path: path
        })
      },
      // 暂未用到
      toArticleHome(id) {
        this.$router.$avueRouter.closeTag()
        const path = '/knowledge/index'
        this.$router.push({
          path: path,
          query: {
            knowledgeCategoryId: id
          }
        })
      },
      // 修改按钮事件
      editArticle() {
        let path = '/kbpArticleAdd'
        if (this.myObj.type == 2) {
          path = '/kbpQuestionAdd'
        }
        this.$router.push({
          path: path,
          query: {
            id: this.id,
            knowledgeType: this.myObj.type
          }
        })
      },
      // 删除按钮事件
      delArticle() {
        const that = this
        this.$confirm('确认删除此知识点?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delArticle({ ids: that.id }).then(res => {
            if (res.data.code == 200) {
              that.$message({ message: '删除成功', type: 'success' })
              // that.$router.$avueRouter.closeTag();
              that.$router.go(-1)
            }
          })
        })
      },
      // 下载附件
      download(file) {
        if (file && file.path) {
          window.open(window.CONFIG.fileServer + '/get?filename=' + file.path)
        } else {
          this.$message({ message: '附件路径为空，不能下载！', type: 'warning' })
        }
      },
      // 转换office为pdf
      changeOffice (url) {
        let newUrl = window.CONFIG.fileServer + '/get?filename=' + url
        const officeReg = /\.pdf$/
        const excelReg = /\.(xls|xlsx)$/
        if (officeReg.test(url)) {
          // this.iframeQuery = { pdfLink: url, pdfFlag: 1 }
          if (this.resourceType == 4) {
            let data = { pdfLink: url, pdfFlag: 1 }
            window.eventEmitter.$emit('iframeViewEvent', data)
          } else {
            const new1 = this.$router.resolve({ path: '/frameView', query: { pdfLink: url, pdfFlag: 1 } })
            window.open(new1.href, '_blank')
          }
        } else if (excelReg.test(url)) {
          // 解析excel
          getExcelData(url).then(res => {
            const data = new Uint8Array(res.data)
            const workbook = xlsx.read(data, { type: 'array' })
            if (this.resourceType == 4) {
              let data = { workbook: JSON.stringify(workbook) }
              window.eventEmitter.$emit('iframeViewEvent', data)
            } else {
              const new1 = this.$router.resolve({ path: '/frameView', query: { workbook: JSON.stringify(workbook) } })
              const temppage = window.open('', '_blank')
              temppage.location = new1.href
              // window.open(new1.href, '_blank')
            }
          })
        } else {
          changeToPdf(newUrl).then(res => {
            const binaryData = []
            binaryData.push(res.data)
            const pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
            if (this.resourceType == 4) {
              let data = { pdfLink: pdfUrl }
              window.eventEmitter.$emit('iframeViewEvent', data)
            } else {
              // window.open(pdfUrl, '_blank')
              const new1 = this.$router.resolve({ path: '/frameView', query: { pdfLink: pdfUrl } })
              window.open(new1.href, '_blank')
            }
          })
        }
      },
      initData() {
        const self = this
        if (self.id) {
          getArticleById({ id: self.id }).then(res => {
            self.myObj = res.data.data
            if (self.myObj.starStatus == 1) {
              self.collectImg = 'assets/theme/img/select_collect.png'
            } else {
              self.collectImg = 'assets/theme/img/default_collect.png'
            }
            if (self.myObj.agreeStatus == 1) {
              self.agreeImg = 'assets/theme/img/confirm_agree_img.png'
            } else {
              self.agreeImg = 'assets/theme/img/agree_img.png'
            }
            if (self.myObj.notAgreeStatus == 1) {
              self.notAgreeImg = 'assets/theme/img/confirm_not_agree_img.png'
            } else {
              self.notAgreeImg = 'assets/theme/img/not_agree_img.png'
            }
            if (self.myObj.tags) {
              self.tags = self.myObj.tags.split(',')
            }
            // 处理附件格式，判断是否显示查看按钮
            self.myObj.knowledgeArticleFileList.forEach(item => {
              const reg = /(flv|mp4|wmv|flv|f4v|3gp|rm|rmvb|avi|asf|mpg|mpeg|mpe|ts|jpg|jpeg|png|PNG|JPG|JPEG|gif|svg|doc|pdf|docx|pptx|ppt|xls|xlsx)/
              if (reg.test(item.name.split('.').slice(-1))) {
                item.showView = true
              } else {
                item.showView = false
              }
              if (self.resourceType == 4) {
                self.changeOffice(item.path)
              }
            })
            if (self.myObj.graphStr) {
              setTimeout(function() {
                var myChart = echarts.init(document.getElementById('graphDiv'))
                var graph = JSON.parse(self.myObj.graphStr)
                var categories = []
                var keyWordArr = self.myObj.keyWord.split(',')
                for (let i = 0; i < keyWordArr.length; i++) {
                  categories[i] = {
                    name: keyWordArr[i]
                  }
                }
                graph.nodes.forEach(function(node) {
                  node.itemStyle = null
                  // node.value = node.symbolSize;
                  node.symbolSize /= 1.5
                  node.label = {
                    show: node.symbolSize > 30
                  }
                  node.category = node.attributes.modularity_class
                })
                const option = {
                  tooltip: {},
                  legend: [{
                    // selectedMode: 'single',
                    data: categories.map(function(a) {
                      return a.name
                    })
                  }],
                  animationDuration: 1500,
                  animationEasingUpdate: 'quinticInOut',
                  series: [
                    {
                      name: '关联知识',
                      type: 'graph',
                      layout: 'none',
                      data: graph.nodes,
                      links: graph.links,
                      categories: categories,
                      roam: true,
                      focusNodeAdjacency: true,
                      itemStyle: {
                        borderColor: '#fff',
                        borderWidth: 1,
                        shadowBlur: 10,
                        shadowColor: 'rgba(0, 0, 0, 0.3)'
                      },
                      label: {
                        position: 'right',
                        formatter: '{b}'
                      },
                      lineStyle: {
                        color: 'source',
                        curveness: 0.3
                      },
                      emphasis: {
                        lineStyle: {
                          width: 10
                        }
                      }
                    }
                  ]
                }
                myChart.setOption(option)
                myChart.on('click', function(param) {
                  if (param.dataType == 'node') {
                    self.$router.push({
                      path: '/kbpDetail',
                      query: {
                        id: param.data.id
                      }
                    })
                  }
                })
              }, 500)
            }
          })
        } else {
          console.log('init id is null!!!')
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

  .el-divider--horizontal {
    margin: 10px 0px 0px;
  }

  .v-note-wrapper {
    height: auto;
    min-height: 0px;
  }

  .commentIconFixed {
    position: fixed;
    overflow: hidden;
    right: -25px;
    bottom: 45%;
    z-index: 999;
    width: 80px;
  }

  .commentIcon img {
    width: 20px;
    height: 20px;
    vertical-align: middle;
    cursor: pointer
  }
  /deep/ .v-note-wrapper .v-note-panel .v-note-show .v-show-content, .v-note-wrapper .v-note-panel .v-note-show .v-show-content-html {
    overflow-x: auto;
  }
  .commentIcon div {
    display: inline-block;
    height: 20px;
    margin-left: 5px;
    color: #666666;
    font-size: 14px;
  }

  .line-height {
    line-height: 28px;
  }

  .markdown-body {
    border: none;
  }

  .know-title {
    margin: 20px 0px;
    color: #8F8F91;
    font-size: 14px;
  }

  .know-content {
    color: #8F8F91;
    font-size: 14px;
  }

  .know-content .markdown-body {
    font-size: 14px;
    padding: 0px;
    line-height: 24px;
    color: #333333;
  }

  .commentDiv {
    width: 100%;
    height: auto;
    overflow: hidden;
  }

  .commentDiv .el-divider--horizontal {
    margin: 0px;
  }

  .commentDiv img{
    width: 100%;
    height: 100%;
    margin: 10px 5px 10px 0px;
  }

  .commentName{
    line-height: 34px;
    color: #8F8F91;
    font-size: 13px;
  }

  .preImg {
    position: fixed;
    z-index: 99999;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    background: rgba($color: #000000, $alpha: 0.7);
    img {
      width: auto;
      height: auto;
      transform: scaleX(1);
      transform: scaleY(1);
      position: absolute;
      top: 6%;
    }
  }
</style>
